#include "settingshandler.h"

#include "../mainwindow.h"
#include "../perspectives/simulationperspective.h"
#include "documentmanager.h"
#include "../documents/data/graphicdata.h"

#include <idocumentdata.h>

#include <QtCore/QVariant>

using namespace core;
using namespace swp;

SettingsHandler* settingsHandler = 0;

SettingsHandler* SettingsHandler::getInstance()
{
    if (settingsHandler == 0)
    {
        settingsHandler = new SettingsHandler();
    }

    return settingsHandler;
}

void SettingsHandler::destroy()
{
    delete settingsHandler;
    settingsHandler = 0;
}

void SettingsHandler::notify(core::IObservableObject *source,
    const QString &property, const QVariant &value)
{
    if (property == "SnapToGrid")
    {
        handleSnapToGrid(value.toBool());
    }
    else if (property == "DefaultRepetitions")
    {
        MainWindow::getInstance()->m_simulationPerspective->
            setDefaultsForSimulationDialog(value.toInt(), -1);
    }
    else if (property == "DefaultTimeout")
    {
        MainWindow::getInstance()->m_simulationPerspective->
            setDefaultsForSimulationDialog(-1, value.toInt());
    }
}

SettingsHandler::SettingsHandler()
{

}

SettingsHandler::~SettingsHandler()
{

}

void SettingsHandler::handleSnapToGrid(bool value) const
{
    DocumentManager* dm = DocumentManager::getInstance();

    QList<QSharedPointer<IDocument> > documents = dm->openedDocuments();

    foreach (const QSharedPointer<IDocument>& document, documents)
    {
        IDocumentData* data = document->data();

        if (data->type() == IDocumentData::GraphicModel)
        {
            GraphicData* _data  = dynamic_cast<GraphicData*>(data);

            if (_data != 0)
            {
                _data->setSnapToGrid(value);
            }
        }
    }
}
